﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Data.SqlClient;
using System.Data;
using XLugia.Lib.XDataBase.Base.Lib;
using XLugia.Lib.XDataBase.Base.Model;

namespace XLugia.Lib.XDataBase.Engine.MSSQL.Lib
{
    /// <summary>
    /// 数据库脚本执行控制器
    /// </summary>
    public class MSSQLExecutor : DatabaseExecutor
    {
        /// <summary>
        /// 数据库脚本执行控制器
        /// </summary>
        /// <param name="databaseConnector">数据库连接器。</param>
        public MSSQLExecutor(DatabaseConnector databaseConnector)
            : base(new DatabaseConnector()
            {
                connectionString = databaseConnector.connectionString,
                commandTimeout = databaseConnector.commandTimeout,
                databaseType = databaseConnector.databaseType,
                isolationLevel = databaseConnector.isolationLevel,
                metadata = "metadata=res://*/Metadata.DatabaseModel.csdl|res://*/Metadata.DatabaseModel.ssdl|res://*/Metadata.DatabaseModel.msl;provider=System.Data.SqlClient;provider connection string=\"" + databaseConnector.connectionString + "\""
            })
        {
        }

        #region MSSQL大批量高速数据插入
        /// <summary>
        /// 将DataTable中的数据大批量高速写入至数据库。
        /// </summary>
        /// <param name="sqlDataTable">DataTable数据源</param>
        public void executeMSSQLBulkSqlCommand(DataTable sqlDataTable)
        {
            try
            {
                using (var dbo = new DatabaseEntities(base.databaseConnector))
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(dbo.Database.Connection.ConnectionString))
                {
                    bulkCopy.BulkCopyTimeout = dbo.Database.Connection.ConnectionTimeout;
                    bulkCopy.DestinationTableName = sqlDataTable.TableName;
                    foreach (DataColumn dc in sqlDataTable.Columns)
                    {
                        bulkCopy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);
                    }

                    bulkCopy.WriteToServer(sqlDataTable);
                    sqlDataTable.Dispose();
                    bulkCopy.Close();
                }
            }
            catch (Exception ex)
            {
                throw DatabaseException.getSqlException("executeMSSQLBulkSqlCommand", sqlDataTable, ex);
            }
        }
        #endregion
    }
}
